package middleware

import (
	"bytes"
	"gitee.com/chejiangyi/bsfgo/core/base2"
	"gitee.com/chejiangyi/bsfgo/core/utils"
	"gitee.com/chejiangyi/bsfgo/gin2/utils2"
	"github.com/gin-gonic/gin"
	"io"
)

type CacheBodyMiddleware struct{}

func (*CacheBodyMiddleware) GetOrder() float64 {
	return -99
}
func (m *CacheBodyMiddleware) Enabled() bool {
	return base2.BsfConfigInstance.GetCacheBodyEnabled()
}
func (*CacheBodyMiddleware) Middleware(r *gin.Engine) {
	r.Use(func(c *gin.Context) {
		// 只处理json请求
		if utils2.WebUtil.HeaderContentTypeIsJson(c) {
			bodyBytes, _ := io.ReadAll(c.Request.Body)
			//重置
			c.Request.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
			//缓存
			utils2.WebUtil.SetBodyCache(c, bodyBytes)
		}
		c.Next()
	})
	utils.LogUtil.Info("CacheBodyMiddleware已开启,Request Body支持缓存读取")
}
